/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2024-11-26 20:45:29
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2024-11-26 20:59:17
 * @FilePath: /zhuang/Demo/testCond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>
using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *active(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        // 我想让所有新线程听我指挥
        // 没有对资源的就绪判定
        // 所有线程先去指定条件变量等而且抱着锁，但是这样其他线程就进不来
        pthread_cond_wait(&cond, &mutex); // 去cond等   自动释放传进来的锁
        // 未来唤醒时会重新持有锁
        printf("%s is active!\n", name.c_str());
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, nullptr, active, (void *)"thread-1");
    pthread_create(&tid2, nullptr, active, (void *)"thread-2");
    pthread_create(&tid3, nullptr, active, (void *)"thread-3");

    sleep(1);
    printf("Main thread ctrl begin..\n");
    while (true)
    {
        // 唤醒指定条件变量下等待的线程
        printf("Main wakeup thread..\n");
        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        sleep(1);
    }
    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);

    return 0;
}